import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv


filename1=r'F:\AI\right03.jpg'
img1=cv.imread(filename1)
filename2=r'F:\AI\right04.jpg'
img2=cv.imread(filename2)

gray1=cv.cvtColor(img1,cv.COLOR_BGR2GRAY)
gray2=cv.cvtColor(img2,cv.COLOR_BGR2GRAY)

surf=cv.xfeatures2d_SURF.create(hessianThreshold=800)
k1,d1=surf.detectAndCompute(gray1,None)
k2,d2=surf.detectAndCompute(gray2,None)

bf = cv.BFMat.Bcher(cv.NORM_L2)
matches=bf.match(d1,d2)
img3=cv.drawMatches(img1,k1,img2,k2,matches,None,flags=2)
cv.imshow('SURF',img3)

FLANN_INDEX_KDTREE=0
#设置FLANN超参数，FLANN最快速近邻搜索包，FLANN匹配需要两个字典（dict）index_params；search_params
index_params=dict(algorithm=FLANN_INDEX_KDTREE,tree=5)#K-D树索引超参数
search_params=dict(checks=50)#设置遍历次数，次数越高越准确但时间会长
flann=cv.FlannBasedMatcher(index_params,search_params)#初始化LannBasedMatcher匹配器
#BFMatcher是暴力搜索，FlannBasedMatcher是一种优化后的最近邻搜索方式
matches=flann.knnMatch(d1,d2,k=2)#匹配两张图特征向量

good = []
for i, (m, n) in enumerate(matches):
    if m.distance < 0.6 * n.distance:
        good.append(m)
img3 = cv.drawMatches(img1, k1, img2, k2, good, None, flags=2)
cv.imshow("SURF", img3)
cv.waitKey(0)

